//
//  AddressSelector.m
//  111
//
//  Created by WuXushun on 16/2/22.
//  Copyright © 2016年 wuxushun. All rights reserved.
//

#import "AddressSelector.h"
#import "AddressList.h"
#import "Animation.h"

@interface AddressSelector ()<UIPickerViewDataSource,UIPickerViewDelegate>

@property (nonatomic,assign) CGRect currentRect;
@property (nonatomic,assign) BOOL isShow;;
@property (nonatomic,assign) NSInteger cityRow;
@property (nonatomic,assign) NSInteger areaRow;
@property (nonatomic,assign) NSInteger provinceRow;
@property (nonatomic,strong) NSArray *sourceData;
@property (nonatomic,strong) UIPickerView *picker;
@property (nonatomic,strong) UIView *mainView;


@end

@implementation AddressSelector
@synthesize picker;

- (id)initWithFrame:(CGRect)frame withData:(NSArray *)data{
    
    self = [super initWithFrame:frame];
    
    if (self) {
        
        if (data == nil || ![data isKindOfClass:[NSArray class]]) {
            
            self.cityRow = 0;
            self.provinceRow = 0;
            self.currentRect = frame;
            AddressList *list = [[AddressList alloc]init];
            self.sourceData = [list handlePlist];
            [self initSelf];
            [self initPicker];
            [self initToolBar];
            
        }else{
            
            NSMutableArray *temp = [NSMutableArray new];
            
            for (id obj in data) {
                
                if ([obj isKindOfClass:[NSString class]]) {
                    
                    [temp addObject:obj];
                    
                }
                
            }
            
            if (temp.count > 0) {
                
                self.cityRow = 0;
                self.provinceRow = 0;
                self.currentRect = frame;
                AddressList *list = [[AddressList alloc]init];
                self.sourceData = [list dataFilterWithArray:data];
                [self initSelf];
                [self initPicker];
                [self initToolBar];
                
            }else{
                
                self.cityRow = 0;
                self.provinceRow = 0;
                self.currentRect = frame;
                AddressList *list = [[AddressList alloc]init];
                self.sourceData = [list handlePlist];
                [self initSelf];
                [self initPicker];
                [self initToolBar];
                
            }
            
        }
        
    }
    
    return self;
    
}

-(void)initSelf{
    
    [self setFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height)];
    
    self.backgroundColor = [UIColor clearColor];
    
    self.mainView = [[UIView alloc]initWithFrame:CGRectMake(self.currentRect.origin.x, [[UIScreen mainScreen] bounds].size.height, self.currentRect.size.width, self.currentRect.size.height)];
    self.mainView.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.mainView];
    
}

-(void)initToolBar{
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor colorWithRed:0.f / 255.f green:122.f / 255.f blue:255.f / 255.f alpha:1.f] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelBtnActive:) forControlEvents:UIControlEventTouchUpInside];
    [self.mainView addSubview:cancelBtn];
    NSLayoutConstraint *constraintCancelLeft = [NSLayoutConstraint constraintWithItem:cancelBtn
                                                                           attribute:NSLayoutAttributeLeft
                                                                           relatedBy:NSLayoutRelationEqual
                                                                              toItem:self.mainView
                                                                           attribute:NSLayoutAttributeLeft
                                                                          multiplier:1.f
                                                                            constant:10.f];
    
    NSLayoutConstraint *constraintCanceTop = [NSLayoutConstraint constraintWithItem:cancelBtn
                                                                            attribute:NSLayoutAttributeTop
                                                                            relatedBy:NSLayoutRelationEqual
                                                                               toItem:self.mainView
                                                                            attribute:NSLayoutAttributeTop
                                                                           multiplier:1.f
                                                                             constant:8.f];
    
    
    [self addConstraints:@[constraintCancelLeft,constraintCanceTop]];
    
    UIButton *donelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    donelBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [donelBtn setTitle:@"确定" forState:UIControlStateNormal];
    [donelBtn setTitleColor:[UIColor colorWithRed:0.f / 255.f green:122.f / 255.f blue:255.f / 255.f alpha:1.f] forState:UIControlStateNormal];
    [donelBtn addTarget:self action:@selector(doneBtnActive:) forControlEvents:UIControlEventTouchUpInside];
    [self.mainView addSubview:donelBtn];
    NSLayoutConstraint *constraintDoneLeft = [NSLayoutConstraint constraintWithItem:donelBtn
                                                                            attribute:NSLayoutAttributeRight
                                                                            relatedBy:NSLayoutRelationEqual
                                                                               toItem:self.mainView
                                                                            attribute:NSLayoutAttributeRight
                                                                           multiplier:1.f
                                                                             constant:-10.f];
    
    NSLayoutConstraint *constraintDoneTop = [NSLayoutConstraint constraintWithItem:donelBtn
                                                                          attribute:NSLayoutAttributeTop
                                                                          relatedBy:NSLayoutRelationEqual
                                                                             toItem:self.mainView
                                                                          attribute:NSLayoutAttributeTop
                                                                         multiplier:1.f
                                                                           constant:8.f];
    
    
    [self addConstraints:@[constraintDoneLeft,constraintDoneTop]];

}

-(void)initPicker{

    picker = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 40, self.currentRect.size.width, self.mainView.frame.size.height- 40)];
    picker.backgroundColor = [UIColor whiteColor];
    picker.dataSource = self;
    picker.delegate = self;
    [self.mainView addSubview:picker];
    

}

-(void)cancelBtnActive:(id)sender{
    
    [self hide];

}

-(void)doneBtnActive:(id)sender{

    [self.delegate addressSelectorDidSelected:self withSelectedData:@[[[self.sourceData objectAtIndex:[self.picker selectedRowInComponent:0]] objectForKey:@"provinceName"],
                                                                      [[[[self.sourceData objectAtIndex:self.provinceRow] objectForKey:@"cityList"]objectAtIndex:[self.picker selectedRowInComponent:1]] objectForKey:@"cityName"],
                                                                      [[[[[self.sourceData objectAtIndex:self.provinceRow] objectForKey:@"cityList"] objectAtIndex:[self.picker selectedRowInComponent:1]] objectForKey:@"AreaList"] objectAtIndex:[self.picker selectedRowInComponent:2]]]];
    
    [self hide];

}

-(void)show{

    if (!self.isShow) {
        
        UIWindow *win = [[UIApplication sharedApplication] keyWindow];
        UIView *topView = [win.subviews firstObject];
        
        [topView addSubview:self];
        
        CGMutablePathRef path = CGPathCreateMutable();
        CGPathMoveToPoint(path, NULL, 0, self.currentRect.origin.y + self.currentRect.size.height);
        CGPathAddLineToPoint(path, NULL, 0, self.currentRect.origin.y - 15);
        CGPathAddLineToPoint(path, NULL, 0, self.currentRect.origin.y);
        
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
        
        CAKeyframeAnimation *ani =  [Animation AnimationWithTime:0.5f withPath:path withCompleted:^{
            
            self.isShow = 1;
            [self.mainView.layer removeAnimationForKey:@"anim"];
            
        }];
        
        [self.mainView.layer setAnchorPoint:CGPointMake(0, 0)];
        [self.mainView.layer setPosition:CGPointMake(0, self.currentRect.origin.y)];
        [self.mainView.layer addAnimation:ani forKey:@"anim"];
        
    }

}

-(void)hide{

    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, self.currentRect.origin.y);
    CGPathAddLineToPoint(path, NULL, 0, self.currentRect.origin.y - 15);
    CGPathAddLineToPoint(path, NULL, 0, self.currentRect.origin.y + self.currentRect.size.height);
    
    CAKeyframeAnimation *ani =  [Animation AnimationWithTime:0.5f withPath:path withCompleted:^{
        
        self.backgroundColor = [UIColor clearColor];
        self.isShow = 0;
        [self.mainView.layer removeAnimationForKey:@"ani"];
        [self removeFromSuperview];
        
    }];
    
    [self.mainView.layer setAnchorPoint:CGPointMake(0, 0)];
    [self.mainView.layer setPosition:CGPointMake(0, self.currentRect.origin.y + self.currentRect.size.height)];
    [self.mainView.layer addAnimation:ani forKey:@"ani"];

}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{

    if (component == 0) {
        
        return self.sourceData.count;
        
    }else if (component == 1){
    
        NSArray *temp = [[self.sourceData objectAtIndex:self.provinceRow] objectForKey:@"cityList"];
        return temp.count;
    
    }else{
    
        NSArray *temp = [[[[self.sourceData objectAtIndex:self.provinceRow] objectForKey:@"cityList"] objectAtIndex:self.cityRow] objectForKey:@"AreaList"];
        return temp.count;
    
    }

}



-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{

    if (component == 0) {
        
        return [[self.sourceData objectAtIndex:row] objectForKey:@"provinceName"];
        
    }else if (component == 1){
        
        return [[[[self.sourceData objectAtIndex:self.provinceRow] objectForKey:@"cityList"]objectAtIndex:row] objectForKey:@"cityName"];
        
    }else{

        return [[[[[self.sourceData objectAtIndex:self.provinceRow] objectForKey:@"cityList"] objectAtIndex:self.cityRow] objectForKey:@"AreaList"] objectAtIndex:row];
        
    }

}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{

    return 3;

}

-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{

    return 30;


}


-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{

    return self.currentRect.size.width / 3;

}

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{

    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.textAlignment = NSTextAlignmentCenter;
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:[UIFont boldSystemFontOfSize:13.f]];
    }
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;

}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{

    if (component == 0) {
        
        self.provinceRow = row;
        self.cityRow = 0;
        [picker selectRow:0 inComponent:1 animated:NO];
        [picker selectRow:0 inComponent:2 animated:NO];
        [picker reloadComponent:1];
        [picker reloadComponent:2];
        
    }else if (component == 1){
        
        self.cityRow = row;
        self.areaRow = 0;
        [picker selectRow:0 inComponent:2 animated:NO];
        [picker reloadComponent:2];
        
    }else{
        
        self.areaRow = row;
        
    }
    

}


@end
